import os
import json
import pypinyin
from urllib import request
import uuid
import shutil
bppath='./bp/scripts/musicplayer'
path="./rp/sounds/music/"
import os
def genjson():
    print("开始生成音乐json")
    list = os.listdir('./rp/sounds/music/')
    json = "{\"format_version\":\"1.14.0\",\"sound_definitions\":{"
    for i in range(len(list)):
        name = list[i].split('.')[0]
        jsonn = "\"music."+name+"\":{\"category\":\"music\",\"sounds\":[{\"name\":\"sounds/music/"+name+"\",\"stream\":true}]}"
        json = json + jsonn
        if i+1<len(list):
            json = json + ","
    json = json + "}}"
    print("生成完毕,共"+str(len(list)))
    with open('./rp/sounds/sound_definitions.json','w',encoding="utf-8") as f:
        f.write(json)

def musicList():
    list=os.listdir(path)
    failList=[]
    sucList=[]
    shutil.rmtree(f'{bppath}/lrc')
    os.mkdir(f'{bppath}/lrc')
    with open(f'{bppath}/musicList.js',"w",encoding='utf-8') as f:
                f.write('')
    for i,file in enumerate(list):
        filename=file.split('.')[0]
        # 获取歌曲信息
        data=os.popen(f"ffprobe -v quiet -show_streams -print_format json {path}{file}")
        jsondata=json.loads(data.buffer.read().decode("utf-8"))
        tags=jsondata['streams'][0]['tags']
        title=tags['title']
        artist=tags['artist']
        album=tags['album']
        # 获取专辑英文id
        icontext=''.join(pypinyin.lazy_pinyin(album,style=pypinyin.Style.NORMAL))
        for ii in "*$#@%+-;:\'\"\\/":
                title=title.replace(ii,"")
                artist=artist.replace(ii,"")
                album=album.replace(ii,"")
        for ii in "()?&*$#@%+-;:\'\"\\/ ＜：「ー!」[]，?":
            icontext=icontext.replace(ii,"")
        # 时长及歌词
        time=jsondata['streams'][0]['duration']
        for key in tags:
             if 'lyrics' in key:
                  lyrics=tags.get(key)
                  break
        if lyrics==None:
            lyrics=tags.get('TEXT')
            if(lyrics!=None):
                 lyrics=lyrics.encode('utf8').decode('utf8')
            else:
                 print('无法获取歌词信息:'+file)
        # 生成歌词js，并导入
        lrctext='undefined'
        if lyrics!=None:
            genlrcjs(lyrics,filename)
            lrctext=f"lrc_{filename}"
            with open(f'{bppath}/musicList.js',"a",encoding='utf-8') as f:
                f.write(f'import {{lrc_{filename}}} from "./lrc/lrc_{filename}"\n')
        if title=="":
            failList.append(file)
            continue
        print(title)
        txt=f'{{name:"{title}",singer:"{artist}",album:"{album}",icon:"{icontext}",lyrics:{lrctext},time:"{str(time)}",id:"music.{file.split(".")[0]}"}}'
        sucList.append(txt)
    
    with open(f'{bppath}/musicList.js',"a",encoding='utf-8') as f:
        f.write(f"export const musicList = [{','.join(sucList)}]")
    print("_______________________________\n共"+str(len(list))+"个，无信息:"+str(len(failList))+"个\n无信息的音乐如下：")
    for i in failList:
        print(i)

# 生成歌词js
def genlrcjs(text:str,filename:str):
    for ii in "*$#@%;'\"\\/":
         text=text.replace(ii,"")
    lines=text.split('\n')
    lrclist=[]
    # 解析每一行
    for line in lines:
        time=line[line.find('[')+1:line.find(']')]
        time=parsetime(time)
        if time!=False:
            text=line[line.find(']')+1:]
            text=text.replace('\n','').replace('\r','')
            lrclist.append(f'{{time:{time},text:"{text}"}}')
    # 写入js
    with open(f'{bppath}/lrc/lrc_{filename}.js','w',encoding='utf8') as f:
        f.write(f'export const lrc_{filename}=[{",".join(lrclist)}]')

# 时间转换
def parsetime(timetext:str):
    t=timetext.split(':')
    try:
        ans=round(int(t[0])*60+float(t[1]),2)
    except:
        return False
    return ans

def updatesapi():
    print("正在联网获取SAPI版本...")
    with open('bp/manifest.json','r',encoding='utf8') as f:
        bp=json.load(f)
    with open('rp/manifest.json','r',encoding='utf8') as f:
        rp=json.load(f)
    try:
        latestjson=request.urlopen('https://gitee.com/ykxyx666_admin/music-player-mcbe/raw/master/bp/manifest.json',timeout=5)
        code=latestjson.getcode()
        if code==200:
            cloudbp=json.loads(latestjson.read().decode())
        else:
             raise Exception('获取失败')
        bp['dependencies']=cloudbp['dependencies']
        print(f"获取成功:@minecraft/server:{bp['dependencies'][0]['version']},@minecraft/server-ui:{bp['dependencies'][1]['version']} ")
    except:
        print('联网获取SAPI最新版本失败，将使用本地版本')
    bp['header']['name']=config['name']+"BP"
    bp['header']['uuid']=str(uuid.uuid4())
    rp['header']['uuid']=str(uuid.uuid4())
    rp['header']['name']=config['name']+'RP'
    with open('rp/manifest.json','w',encoding='utf8') as f:
        json.dump(rp,f,indent=4,ensure_ascii=False)
    with open('bp/manifest.json','w',encoding='utf8') as f:
        json.dump(bp,f,indent=4,ensure_ascii=False)

def customize():
    global config
    try:
        with open("./config.json","r",encoding="utf8") as f:
            config=json.loads(f.read())
            if(config['changelrc']==None or config['name']==None):
                    raise Exception("配置错误")
    except:
        print("配置文件错误，将使用默认配置")
        config={"changelrc":True,"name":"音乐播放器"}
    if(config['changelrc']==False):
        os.rename("./rp/ui/hud_screen.json","./rp/ui/hud_screen")
    elif os.path.exists("./rp/ui/hud_screen"):
        os.rename("./rp/ui/hud_screen","./rp/ui/hud_screen.json")
    print(f"包名:{config['name']}，修改版歌词:{config['changelrc']}")
    
     
if __name__=="__main__":
    customize()
    genjson()
    updatesapi()
    musicList()
